/**
 * Created by zhanglihe on 15/11/7.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'collection',
    'template',
    'model',
    'dialog',
    'datepicker'
], function( $, common, ready, Collection, template, Model, dialog ,datepicker) {
    var index = function() {
        this.init();
    };
    index.prototype = {
        init: function() {
            loading();
            this.fetch();
            this.event();
        },

        fetch: function() {
            var _this = this;
            this.collection = new Collection({
                url: _global.url.api + 'customcate',
                condition: {type: '1',cate_id:cate_id},
                model: {
                    url:_global.url.api + 'customcate',
                    event: {
                        '.item-edit:click': 'edit',
                        '.item-remove:click': 'remove',
                        '.show-offline:click': 'sethidden',
                        '.show-online:click': 'setshow',
                        '.edit_listorder:change': 'setlistorder'
                    },
                    edit: function(e) {
                        _this.data = this.data;
                        var model = this;
                        e.preventDefault();
                        _this.dialog = dialog({
                            title:'修改自定义分类',
                            content: template('add-tpl', this.data),
                            width: 600,
                            ok: function() {
                                _this.data.name =$("#title").val();
                                if( _this.data.name==''){
                                    Alert({msg:'请输入分类名称',type:'error'});
                                    return false;
                                }
                                _this.data.img = $("input[name='imgs']").val();
                                var album =[];
                                $("input[name='album']").each(function(e){
                                    album.push($(this).val());
                                });
                                _this.data.album = album.join(',');
                                var urls =[];
                                $("input[name='url']").each(function(e){
                                    urls.push($(this).val());
                                });
                                _this.data.urls = urls.join(',');
                                _this.data.listorder = $('#listorder').val();
                                _this.data.id = _this.data.id;
                                if(model.put()){
                                    _this.collection.reload();
                                    _this.album.clear();
                                };
                            },cancel: function() {
                                _this.album.clear();
                            }
                        });
                        _this.dialog.show();
                        if(this.data.albums.length>=8){
                            $("#upload_show").hide();
                        }else{
                            $("#upload_show").show();
                        }
                        if(this.data.image){
                            $("#btn-upload").hide();
                        }
                        $.each(this.data.albums, function() {
                            var el = $(template('imgalbum-tpl', this));
                            _this.album.add(el);
                        });
                        $('input,select,textarea').on('change', function(e) {
                            _this.change(e);
                        });
                        $('.long_date').on('click', function() {
                            WdatePicker({
                                el:this.id,
                                dateFmt:'yyyy-MM-dd HH:mm:ss'
                            });
                        });
                    },
                    remove: function(e) {
                        e.preventDefault();
                        var model = this;
                        dialog({
                            'content': '确定删除吗?',
                            ok: function() {
                                if(model.del()){
                                    _this.collection.fetch();
                                };
                            }, cancel: function() {}
                        }).show(e.target);
                    },
                    setshow:function(e){
                        e.preventDefault();
                        var id =this.data.id;
                        var model =this;
                        dialog({
                            'content': '确定要继续吗?',
                            ok: function() {
                                if(new Model({
                                        url: _global.url.api + 'customcate_set',
                                        data:{id:id,is_visible:1,act:'show'}
                                    }).put()) {
                                    _this.collection.fetch();
                                };
                            }, cancel: function() {}
                        }).show(e.target);
                    },
                    sethidden:function(e){
                        e.preventDefault();
                        var id =this.data.id;
                        var model =this;
                        dialog({
                            'content': '确定要继续吗?',
                            ok: function() {
                                if(new Model({
                                        url: _global.url.api + 'customcate_set',
                                        data:{id:id,is_visible:0,act:'show'}
                                    }).put()) {
                                    _this.collection.fetch();
                                };
                            }, cancel: function() {}
                        }).show(e.target);
                    },
                    setlistorder:function(e){
                        e.preventDefault();
                        var id = this.data.id;
                        var model =this;
                        var listorder = $('input[name="edit_listorder_' + id + '"]').val();
                        if(new Model({
                                url: _global.url.api + 'customcate_set',
                                data:{id:id,listorder:listorder,act:'order'}
                            }).put()) {
                            _this.collection.fetch();
                        };
                    }
                },
                callback: function() {
                    loaded();
                }
            });
            this.collection.fetch();
        },

        event: function() {
            this.data = {};
            var _this = this;
            //保存
            $('#btn-add').on('click', function(e) {
                _this.data = {};
                e.preventDefault();
                _this.dialog = dialog({
                    title:'添加自定义分类',
                    content: template('add-tpl', {}),
                    width: 600,
                    ok: function() {
                        _this.data.pid =$("#pid").val();
                        _this.data.type =1;
                        _this.data.name =$("#title").val();
                        if( _this.data.name==''){
                            Alert({msg:'请输入分类名称',type:'error'});
                            return false;
                        }
                        _this.data.img = $("input[name='imgs']").val();
                        var album =[];
                        $("input[name='album']").each(function(e){
                            album.push($(this).val());
                        });
                        _this.data.album = album.join(',');
                        var urls =[];
                        $("input[name='url']").each(function(e){
                            urls.push($(this).val());
                        });
                        _this.data.urls = urls.join(',');
                        _this.data.listorder = $('#listorder').val();
                        if(new Model({
                                url: _global.url.api + 'customcate',
                                data: _this.data
                            }).post()) {
                            _this.collection.reload();
                            _this.album.clear();
                        }
                    },cancel: function() {
                        _this.album.clear();
                    }
                });
                _this.dialog.show();
                $('input,select,textarea').on('change', function(e) {
                    _this.change(e);
                });
            });
            $('body').on('click', '.image-remove', function(e) {
                $(this).parent('li').remove();
                $("#btn-upload").show();
            });
            $('body').on('click', '#btn-upload', function(e) {
                _this.upload_dialog = dialog({
                    content: template('upload-tpl', {}),
                    width: 550,
                    ok: function() {
                        console.log('contentWindow',$("#upload-frame")[0].contentWindow.image);
                        var img = $("#upload-frame")[0].contentWindow.image.get();
                        _this.imgPreview(img);
                        $("#btn-upload").hide();
                    }, cancel: function() {}
                });
                _this.upload_dialog.show();
            });
            //上传图片
            $('body').on('click', '#btn-uploads', function(e) {
                _this.upload_dialog = dialog({
                    content: template('uploadalbum-tpl', {}),
                    width: 550,
                    ok: function() {
                        var img = $("#upload-frame")[0].contentWindow.image.get();
                        var num = 0;
                        for(i in img){
                            num ++;
                        }
                        if(num+Number( _this.check_image())>8){
                            Alert({msg:'图片不能多于8张',type:'error'});
                            return false;
                        }
                        _this.imgPreviewalbum(img);
                        if(_this.check_image()>=8){
                            $("#upload_show").hide();
                        }else{
                            $("#upload_show").show();
                        }
                    }, cancel: function() {}
                });
                _this.upload_dialog.show();
            });
            $('#btn-search').on('click', function(e) {
                e.preventDefault();
                _this.collection.condition.keyword = $('input[name="keyword"]').val();
                _this.collection.reload();
            });
            $('#btn-status').find('a').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.is_visible = $(e.target).attr('rel');
                _this.collection.reload();
                $(e.target).addClass('active').siblings().removeClass('active');
            });
        },
        check_image:function(){
            var imgs = this.album.get();
            return imgs.length;
        },
        change: function(e) {
            this.data[$(e.target).attr('name')] = $(e.target).val();
        },
        imgPreview: function(img) {
            console.log('this.data',this.data);
            if(typeof img.id !== 'undefined') {
                this.data.img = img.id;
                $('#img-view').html(template('img-tpl', img));
            }
        },
        imgPreviewalbum: function(img) {
            var _this = this;
            $.each(img, function(n, v) {
                if(typeof v.id !== 'undefined') {
                    _this.album.add($(template('imgalbum-tpl', v)));
                }
            });

        },
        album: {
            default: {
                deleted: false,
                init: function() {
                    $('#album-view').append(this.el);
                    this.event();
                },
                event: function() {
                    var _this = this;
                    this.el.on('click', '.album-remove', function(e) {
                        _this.del(e);
                    }).on('click', '.album-default', function(e) {
                        _this.setDefault(e);
                    });
                },
                del: function(e) {
                    var _this = this;
                    e.preventDefault();
                    this.el.remove();
                    $("#upload_show").show();
                    this.deleted = true;
                },
                setDefault: function(e) {
                    e.preventDefault();
                    this.el.addClass('default').siblings().removeClass('default');
                }
            },
            images: [],
            add: function(el) {
                this.images.push($.extend({el: el}, this.default));
                this.images[this.images.length - 1].init();
            },
            get: function() {
                var images = [];
                $.each(this.images, function() {
                    if(!this.deleted) {
                        images.push(this.el.find('[name="album"]').val());
                    }
                });
                return images;
            },
            clear:function(){
                this.images =[];
            }
        }
    };

    new index();

});